package com.template.templateuser.token.service.impl;

import com.template.templatecommon.constants.Constants;
import com.template.templatecommon.domain.Result;
import com.template.templateuser.common.exception.exceptions.UserRuntimeException;
import com.template.templateuser.common.utils.JedisUtil;
import com.template.templateuser.token.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {
    private static  final String TOKEN_NAME="user_token";
    private static  final String TOKEN_PREFIX="user_token";

    @Autowired
    JedisUtil jedisUtil;
    @Override
    public Result createToken() {
        String str = UUID.randomUUID().toString();
        StringBuilder token = new StringBuilder();
        token.append(TOKEN_PREFIX).append(str);
        jedisUtil.set(token.toString(), token.toString(), Constants.Redis.EXPIRE_TIME_MINUTE);
        return Result.success(token.toString());
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new UserRuntimeException("非法请求");
            }
        }

        if (!jedisUtil.exists(token)) {
            throw new UserRuntimeException("重复请求");
        }

        Long del = jedisUtil.del(token);
        if (del <= 0) {
            throw new UserRuntimeException("重复请求");
        }
    }
}
